package com.lv.suyiyong.hfr.ui

import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DesUtil
import com.lv.common.utils.LiveEventUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserInfo
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.bean.TokenBean
import com.lv.suyiyong.hfr.databinding.ActivitySetPasswordBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/2 7:26 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：设置密码
 */
@Route(path = ARoutUtils.SetPasswordActivity)
class SetPasswordActivity : BaseActivity<ActivitySetPasswordBinding>(),
    View.OnClickListener {
    private var mPhone: String? = null
    private var mId: String? = null
    private var isShowPassWordTop: Boolean = false
    private var isShowPassWordBottom: Boolean = false
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_set_password
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            StatusBarUtil.setHeightAndPadding(this@SetPasswordActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("忘记密码")
            initSingleClickListener(ivEyes, ivEyesP, btnLogin)
        }
    }

    private fun updateUser(partMap: HashMap<String, RequestBody>) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.updateUser(partMap)
                }.await()
            parseUpdateUserResult(result)
        }
    }

    private fun parseUpdateUserResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                LiveEventBus
                    .get(LiveEventUtils.FINISH_SETPASSWORDACTIVITY_KEY, String::class.java)
                    .post("1")
                finish()

            }
            onBizError<TokenBean> { code, message, data ->

            }
        }
    }


    override fun initConfig() {
        super.initConfig()

    }


    override fun initData() {
        super.initData()
        val userInfo = intent.getParcelableExtra<UserInfo>("userInfo")
        mPhone = userInfo?.phone
        mId = userInfo?.id
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.iv_eyes_p -> {
                isShowPassWordTop = !isShowPassWordTop
                if (isShowPassWordTop) {
                    mBinding.ivEyesP.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etPhone.transformationMethod = null
                } else {
                    mBinding.ivEyesP.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etPhone.transformationMethod = PasswordTransformationMethod()
                }
                mBinding.etPhone.setSelection(mBinding.etPhone.text.length)
            }

            R.id.iv_eyes -> {
                isShowPassWordBottom = !isShowPassWordBottom
                if (isShowPassWordBottom) {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etCode.transformationMethod = null
                } else {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etCode.transformationMethod = PasswordTransformationMethod()
                }
                mBinding.etCode.setSelection(mBinding.etCode.text.length)
            }

            R.id.btn_login -> {
                val password = mEditorViewModel.obMobile.get()
                val password_ = mEditorViewModel.obPassword.get()
                if (password != password_) {
                    showToast("输入的密码不一致")
                } else {
                    val partMap = HashMap<String, RequestBody>()
                    partMap["userid"] = YgxNetUtilsKt.partToRequestBody(mId!!)
                    partMap["password"] = YgxNetUtilsKt.partToRequestBody(DesUtil.encode(password))
                    updateUser(partMap)

                }

            }

        }
    }

}